﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

/// <summary>
///mrjapp 的摘要说明
/// </summary>
public class mrjapp
{
    string appid = "0420152741650001";
    string secret = "7XJRWroI0fNqTSRXUnOxfN4C8fIUm/V2/3ElRH/Wnk=";
    static string getmsg;//保存token凭证
    MyDbHelper mydb = new MyDbHelper();
	public mrjapp()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    /*
     * http://192.168.10.53:8086/oauth/token?client_id=mrj-api&grant_type=password&username=0420152741650001&password=7XJRWroI0fNqTSRXUnOxfN4C8fIUm/V2/3ElRH/Wnk=
     * 
        http://192.168.10.53:8086/api?access_token=78cfe9d3-4aa8-4b5c-90e9-4a945d1c55aa&appId=0420152741650001
     */
    public string gettoken()
    {
        string url = "http://192.168.10.53:8086/oauth/token?client_id=mrj-api&grant_type=password&username=" + appid + "&password=" + secret;
        getmsg = GetModel(url);
        if (getmsg != null && getmsg.Trim() != "")
        {
            try
            {
                //解析订单明细的josn
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                JsonObject_token jt = serializer.Deserialize<JsonObject_token>(getmsg);
                if (jt != null)
                {

                    return jt.access_token;
                }
                return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
        return "";
    }
    //http://192.168.10.53:8086/api/shop/listV2?access_token=78cfe9d3-4aa8-4b5c-90e9-4a945d1c55aa
    public void getshoplist()
    {
        string url = "http://192.168.10.53:8086/api/shop/list?appId="+appid+"&access_token="+gettoken();
        string getmsg = GetModel(url);
        //解析josn  //获取关注的人
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        json_reslt getshop = serializer.Deserialize<json_reslt>(getmsg);
        mrjshop[] shoplist = getshop.content;
        string sql = "";
        if (shoplist != null)
        {
            foreach (mrjshop shop in shoplist)
            {
                sql += @" if not exists(select mrjshopid from bas_mrj_shop where mrjshopid ='" + shop.shopid + @"')
                                insert into bas_mrj_shop(mrjshopid,mrjshopcode,mrjshopname,mrjgetdate) values('" + shop.shopid + "','"+shop.shopcode+"','" + shop.shopname + @"',getdate()) 
                            else update bas_mrj_shop set mrjshopcode = '"+shop.shopcode+"',mrjshopname='"+shop.shopname+"' where mrjshopid = '"+shop.shopid+"'";
            }
            mydb.DM_ExecuteNonQuery(sql);
        }

    }
    /*
        获取店铺流量
     * http://192.168.10.53:8086/api/shop/getKpiesData?shopId=5688&dataType=2&beginDate=2016-04-24&endDate=2016-04-24&hasWay=false&access_token=78cfe9d3-4aa8-4b5c-90e9-4a945d1c55aa
     */
    public void getKpiesData(string bdate, string edate, string shopid, string token)
    {
        string url = "http://192.168.10.53:8086/api/shop/getKpiesData?shopId="+shopid+"&dataType=2&beginDate="+bdate+"&endDate="+edate+"&hasWay=false&access_token="+token;
        string getmsg = GetModel(url);
        //解析josn  //获取关注的人
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        json_reslt2 getshop = serializer.Deserialize<json_reslt2>(getmsg);
        if (getshop.status == "-1")
            return;
        JObject jo = (JObject)JsonConvert.DeserializeObject(getmsg);
        string jo_1 = jo["content"]["kpiShopAccountes"][0]["kpiShopAccountDatas"][0]["dataMap"].ToString();
        string jo_2 = jo["content"]["kpiShopAccountes"][1]["kpiShopAccountDatas"][0]["dataMap"].ToString();
        string jo_3 = jo["content"]["kpiShopAccountes"][2]["kpiShopAccountDatas"][0]["dataMap"].ToString();
        
        
        string sql = "";
        //进入客流
        dataMap[] datalist_1 = serializer.Deserialize<dataMap[]>(strtojson(jo_1));
        //出来客流
        dataMap[] datalist_2 = serializer.Deserialize<dataMap[]>(strtojson(jo_2));
        //滞留人数
        dataMap[] datalist_3 = serializer.Deserialize<dataMap[]>(strtojson(jo_3));
        
        foreach (dataMap d in datalist_1)
        {
            sql += @" insert into bas_kpiesdata(shopid,shopname,kpiid,kpiname,kpidate,kpiqty)
                    select '" + shopid + "','','1','进入客流','" + d.getdate + "'," + d.qty + " ";

        }

        foreach (dataMap d in datalist_2)
        {
            sql += @" insert into bas_kpiesdata(shopid,shopname,kpiid,kpiname,kpidate,kpiqty)
                    select '" + shopid + "','','2','出来客流','" + d.getdate + "'," + d.qty + " ";

        }

        foreach (dataMap d in datalist_3)
        {
            sql += @" insert into bas_kpiesdata(shopid,shopname,kpiid,kpiname,kpidate,kpiqty)
                    select '" + shopid + "','','3','滞留人数','" + d.getdate + "'," + d.qty + " ";

        }
        mydb.DM_ExecuteNonQuery(sql);

    }
    //导入店铺POS数据
    public bool ImportshopSaleData(string shopid, string date, string amount, string salecount, string qty)
    {
        string url = "http://192.168.10.53:8086/api/pos/import?shopId=" + shopid + "&access_token=" + gettoken() + "&appId=" + appid;
        string param = "[{\"amount\":" + amount + ",\"tradeDay\":\"" + date + "\",\"tradeNumber\":" + salecount + ",\"quantity\":" + qty + "}]";
        string result = PostModel(url, param);
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        reslt_msg msg = serializer.Deserialize<reslt_msg>(result);
        if (msg.status == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public string strtojson(string jo)
    {
        string tempstr = "[";
        jo = jo.Substring(1, jo.Length - 2);
        string[] str = jo.Split(',');
        foreach (string s in str)
        {
            tempstr += "{\"getdate\":" + s.Substring(1, s.IndexOf("\":") - 1) + "\",\"qty\"" + s.Substring(s.IndexOf("\":") + 1) + "},";
        }
        tempstr = tempstr.TrimEnd(',')+"]";

        return tempstr;
    }
    /// <summary>
    /// get方法
    /// </summary>
    /// <param name="strUrl">传入url</param>
    /// <returns></returns>
    public string GetModel(string strUrl)
    {
        string strRet = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.IO.Stream resStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(resStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            while (count > 0)
            {
                String str = new String(read, 0, count);
                strRet = strRet + str;
                count = readStream.Read(read, 0, 256);
            }
            resStream.Close();
        }
        catch (Exception e)
        {
            strRet = "";
        }
        return strRet;
    }
    /// <summary>
    /// post方法
    /// </summary>
    /// <param name="strUrl">传入url</param>
    /// <param name="strParm">传入参数</param>
    /// <returns></returns>
    public string PostModel(string strUrl, string strParm)
    {
        Encoding encode = System.Text.Encoding.UTF8;
        byte[] arrB = encode.GetBytes(strParm);

        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(strUrl);
        myReq.Method = "POST";
        //myReq.ContentType = "application/x-www-form-urlencoded";
        myReq.ContentType = "application/json";
        myReq.ContentLength = arrB.Length;
        Stream outStream = myReq.GetRequestStream();
        outStream.Write(arrB, 0, arrB.Length);
        outStream.Close();
        WebResponse myResp = null;
        try
        {
            //接收HTTP做出的响应
            myResp = myReq.GetResponse();
        }
        catch (Exception e)
        {
            int ii = 0;
        }
        Stream ReceiveStream = myResp.GetResponseStream();
        StreamReader readStream = new StreamReader(ReceiveStream, encode);
        Char[] read = new Char[256];
        int count = readStream.Read(read, 0, 256);
        string str = null;
        while (count > 0)
        {
            str += new String(read, 0, count);
            count = readStream.Read(read, 0, 256);
        }
        readStream.Close();
        myResp.Close();
        return str;
    }


 /// <summary>
    /// token的实体类
    /// </summary>
    public class JsonObject_token
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
    }

 /// <summary>
    /// jstoken的实体类
    /// </summary>
    public class JsonObject_jstoken
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public string expires_in { get; set; }
        public string scope { get; set; }
    }
    public class reslt_msg
    {
        public int status{get;set;}
        public string msg{ get; set; }
        public int content { get; set; }
    }
    public class json_reslt
    {
        public string status { get; set; }
        public mrjshop[] content { get; set; }
    }
    public class json_reslt2
    {
        public string status { get; set; }
        public mrjshop content { get; set; }
    }
    public class mrjshop
    {
        public string shopid { get; set; }
        public string shopname { get; set; }
        public string shopcode { get; set; }
        public kpiShopAccountes[] shopacc { get; set; }
    }
    public class kpiShopAccountes{
        public string kpiId { get; set; }
        public string kpiName { get; set; }
        public kpiShopAccountDatas[] shopaccdata { get; set; }
    }
    public class kpiShopAccountDatas
    {
        public dataMap[] datalist { get; set; }
    }
    public class dataMap
    {
        public string getdate { get; set; }
        public string qty { get; set; }
    }
}